package com.example.demo.controller;

import com.example.demo.dto.*;
import com.example.demo.entity.User;
import com.example.demo.exception.BadRequestException;
import com.example.demo.service.DeptService;
import com.example.demo.service.RoleService;
import com.example.demo.service.UserService;
import com.example.demo.utils.ResultUtils;
import com.example.demo.utils.SecurityUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.*;
import java.util.stream.Collectors;

@Slf4j
//返回json格式的数据
@RestController
//映射请求
@RequestMapping("/user")
@Api(tags = "系统：用户管理")
public class UserController {
    @Autowired
    private UserService userService;
    @Autowired
    private DeptService deptService;
    @Autowired
    private RoleService roleService;
    @Autowired
    private PasswordEncoder passwordEncoder;

    @ApiOperation("查询用户")
    @PostMapping("/list")
    @PreAuthorize("@el.check('user:list')")
    public ResponseEntity<Object> getUsers(UserQueryCriteria criteria){
        if(criteria.getCreateTime() !=null && criteria.getCreateTime().size()>0){
            if(criteria.getCreateTime().get(1).before(criteria.getCreateTime().get(0))){
                return new ResponseEntity<>(ResultUtils.error("操作失败，查询时间段设置不正确"), HttpStatus.OK);
            }
        }
        List<UserDto> userList=buildDtos(userService.findAll(criteria));

        return new ResponseEntity<>(ResultUtils.ok("查询用户信息成功").put("userList",userList),HttpStatus.OK);

    }
    public UserDto buildDto(UserDto user){
        DeptSmallDto deptSmallDto = new DeptSmallDto();
        DeptDto dept =deptService.findById(user.getDeptId());
        deptSmallDto.setDeptName(dept.getDeptName());
        deptSmallDto.setId(user.getDeptId());
        user.setDept(deptSmallDto);

        RoleSmallDto roleSmallDto = new RoleSmallDto();
        RoleDto role=roleService.findById(user.getRoleId());
        roleSmallDto.setId(user.getRoleId());
        roleSmallDto.setName(role.getRoleName());
        roleSmallDto.setLevel(role.getLevel());
        roleSmallDto.setDataScope(role.getDataScope());
        user.setRole(roleSmallDto);
        return user;
    }

    public List<UserDto> buildDtos(List<UserDto> lists){
        List<UserDto> new_lists = new ArrayList<>();
        for (UserDto user:lists) {
            new_lists.add(buildDto(user));
        }
        return new_lists;
    }
    @ApiOperation("修改用户")
    @PostMapping("/update")
    @PreAuthorize("@el.check('user:edit')")
    public ResponseEntity<Object> update(@Validated(User.Update.class) @RequestBody User resources){
        if(resources.getRoleId()!=null){
            //判断角色的等级
            checkLevel(resources);
        }
        UserDto userInfo=userService.findById(resources.getId());
        if(!userInfo.getPassword().equals(resources.getPassword())){
            resources.setPassword(passwordEncoder.encode(resources.getPassword()));
        }
        userService.update(resources);
        return new ResponseEntity<>(ResultUtils.ok("用户信息修改成功"),HttpStatus.OK);
    }

    /**
     * 如果当前用户的角色级别低于创建用户的角色级别，抛出异常信息提示权限不足
     * @param resources
     */
    private void checkLevel(User resources){
        //1、当前登录用户是谁，查找登录用户的级别
        UserDto user=userService.findByName(SecurityUtils.getUsername());
        Integer cu_level = Collections.min(roleService.findByUsersId(user.getId()).stream().map(RoleSmallDto::getLevel).collect(Collectors.toList()));

        //2、判断需要修改的用户信息中的角色级别
        Integer opt_level=roleService.findByRoleId(resources.getRoleId());
        if(cu_level>opt_level){
            throw new BadRequestException("角色权限不足");
        }
    }

    @ApiOperation("查询用户详情")
    @PostMapping("/queryInfo")
    @PreAuthorize("@el.check('user:list')")
    public ResponseEntity<Object> queryInfo(Long id){
        UserDto userInfo = buildDto(userService.findById(id));
        return new ResponseEntity<>(ResultUtils.ok("查询用户详情成功").put("userInfo",userInfo),HttpStatus.OK);
    }

    @ApiOperation("删除用户")
    @PostMapping("/del")
    @PreAuthorize("@el.check('user:del')")
    public ResponseEntity<Object> delete(@RequestBody UserQueryCriteria criteria){
        //查询当前登录用户
        UserDto user = userService.findByName(SecurityUtils.getUsername());
        for (Long id:criteria.getIds()){
            //获取等钱登录用户的角色级别
            Integer cuLevel = Collections.min(roleService.findByUsersId(user.getId()).stream().map(RoleSmallDto::getLevel).collect(Collectors.toList()));
            //获取需要删除的用户的角色级别
            Integer optLevel = Collections.min(roleService.findByUsersId(id).stream().map(RoleSmallDto::getLevel).collect(Collectors.toList()));
            if(cuLevel>optLevel){
                throw new BadRequestException("");
            }
        }
        userService.delete(criteria.getIds());
        return new ResponseEntity<>(ResultUtils.ok("删除成功"),HttpStatus.OK);
    }




}
